package org.uned.agonzalo16.bitacora.web.blog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.uned.agonzalo16.bitacora.dao.ArticleDao;
import org.uned.agonzalo16.bitacora.dao.BlogDao;
import org.uned.agonzalo16.bitacora.domain.Article;
import org.uned.agonzalo16.bitacora.domain.Blog;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;
import org.uned.agonzalo16.bitacora.service.security.AuthenticationProvider;
import org.uned.agonzalo16.bitacora.web.comment.CommentForm;

@RequestMapping("/blog")
@Controller
public class BlogController {

	@Autowired
	private BlogDao blogDao;

	@Autowired
	private ArticleDao articleDao;

	@Autowired
	private AuthenticationProvider authenticationProvider;

	@RequestMapping(method = RequestMethod.GET, value = "/{id}")
	public String show(@PathVariable("id") Long id, @RequestParam(value = "day", required = false) String day, Model model) {
		Blog blog = blogDao.get(id);
		model.addAttribute("blog", blog);

		List<Article> articles = articleDao.findByBlog(blog);

		if (day != null) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
				Date dayDate = sdf.parse(day);
				List<Article> filteredArticles = new ArrayList<Article>();
				for (Article article : articles) {
					if (DateUtils.isSameDay(dayDate, article.getCreationDate())) {
						filteredArticles.add(article);
					}
				}
				model.addAttribute("articles", filteredArticles);
			} catch (ParseException e) {
				model.addAttribute("articles", articles);
			}
		} else {
			model.addAttribute("articles", articles);
		}

		Set<Date> dates = new HashSet<Date>();
		for (Article article : articles) {
			dates.add(article.getCreationDate());
		}
		model.addAttribute("dates", dates);

		AuthenticatedUser user = authenticationProvider.getCurrentUserDetails();

		if (user == null) {
			return "blog/show";
		} else {
			model.addAttribute("comment", new CommentForm(id));
			return "blog/showAndMenu";
		}
	}
}
